package cn.cnnic.uploadkit.handler.impl;

import java.io.ByteArrayOutputStream;
import java.util.Map;

import cn.cnnic.uploadkit.bean.FormFile;
import cn.cnnic.uploadkit.handler.FormHandler;
import static cn.cnnic.uploadkit.MultipartFormdataUtil.*;

public class FileHandler implements FormHandler {
	public int get(int index, StringBuilder buffer, byte[] data, String boundary, Map<String, String> contentParmeter, Map<String, Object> parameters) {
		index = readLine(data, buffer, index);
		String contentType = getContentType(clearBuffer(buffer));
		String line = null;

		readLine(data, buffer, index);
		line = clearBuffer(buffer);

		if (contentType.indexOf("text") > -1) {
			return 0;
		} else {
			ByteArrayOutputStream datastream = new ByteArrayOutputStream();
			boolean isLoop = true;

			if (!isEnd(line, boundary) && !isDataEnd(data, index, boundary)) {
				while (isLoop) {
					if (((char) data[index]) == '\r' || ((char) data[index]) == '\n') {
						if (isDataEnd(data, index, boundary)) {
							isLoop = false;
						}
					}
					if (isLoop) {
						datastream.write(data[index++]);
						if (((char) data[index]) == '\n') {
							datastream.write(data[index++]);
						}
					}
				}
			}
			byte[] formdata = null;
			if (datastream.size() != 0) {
				formdata = datastream.toByteArray();
			}
			parameters.put(contentParmeter.get("name"), new FormFile(contentParmeter.get("filename"), contentType, formdata));

			index = removeSuffixBlankLine(data, index);
			index = readLine(data, buffer, index);

			return index;
		}
	}
}
